package org.flynenu.ums.dao.impl;

import java.util.List;

import org.flynenu.core.dao.base.BaseDao;
import org.flynenu.core.dao.session.SessionBuilder;
import org.flynenu.ums.common.bean.BeansEnum;
import org.flynenu.ums.common.bean.BeansManager;
import org.flynenu.ums.common.entity.Student;
import org.flynenu.ums.common.entity.Teacher;
import org.flynenu.ums.common.entity.base.User;
import org.flynenu.ums.dao.UserDao;
import org.hibernate.Criteria;


public class UserDaoImpl extends BaseDao implements UserDao {

	@Override
	public User queryUser(int id) {
		@SuppressWarnings("unchecked")
		List<User> users = session().createQuery("From User where id = " + id).list();
		session().close();
		
		User user = null;
		for(User tmp: users){
			
			user = tmp;
		}
		
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> queryUsers(Criteria criter) {
		List<User> list = criter.list();
		
		return list;
	}

	@Override
	public void regist(User user) {
		session().beginTransaction();
		session().save(user);
		session().getTransaction().commit();
		session().close();
	}

	@Override
	public void registStudent(Student student) {
		User user = student.getUser();
		
		session().beginTransaction();
		if(user != null){
			session().save(user);
		}
		
		session().save(student);
		
		session().getTransaction().commit();
		session().close();
		
	}

	@Override
	public void registTeacher(Teacher teacher) {
		User user = teacher.getUser();
		
		session().beginTransaction();
		if(user != null){
			session().save(user);
		}
		
		session().getTransaction().commit();
		session().close();
	}
	
	public static void main(String[] args){
		UserDaoImpl dao = new UserDaoImpl();
		dao.setSession((SessionBuilder) BeansManager.instance().generateBean(BeansEnum.DataSource));
		dao.queryUser(1);
	}

}
